package com.fzkj.bio.消息群发.thread;

import com.fzkj.bio.消息群发.factory.ClientFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * 处理客户端消息
 */
public class ServerHandlerThread implements Runnable {

    private Socket socket;
    public ServerHandlerThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try{
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String msg;
            while((msg = br.readLine()) != null){
                sendMsgToAllClient(msg);
            }
        }catch (Exception e){
//            e.printStackTrace();
            System.out.println("客户端退出");
            // 移除当前客户端
            ClientFactory.removeClient(socket);
        }
    }

    /**
     * 群发消息
     */
    private void sendMsgToAllClient(String msg) {
        try {
            for (Socket client : ClientFactory.getAllClients()) {
                // 获取输出流
                PrintStream ps = new PrintStream(client.getOutputStream());
                ps.println(msg);
                ps.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
